﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace JMT.Data
{
    public sealed class JCollection : IJContainer
    {
        public string Type { get; set; }
        public JCollection Next { get; private set; }

        private List<JContainerUpdate<JModel>> _update;

        ObservableCollection<JModel> _collection;
        public JCollection(string type)
        {
            Type = type;
            _collection = new ObservableCollection<JModel>();
        }

        public void Add(JModel jModel)
        {
            if (this.Type == jModel.Type)
            {
                this._collection.Add(jModel);
            }
            else if (this.Next != null)
            {
                this.Next.Add(jModel);
            }
        }

        public void Remove(JModel jModel)
        {
            if (this.Type == jModel.Type)
            {
                this._collection.Remove(jModel);
            }
            else if (this.Next != null)
            {
                this.Next.Remove(jModel);
            }
        }

        public JModel Get(Guid id)
        {
            JModel jModel = null;
            foreach (var item in _collection)
	        {
                if (item.Id == id)
                {
                    jModel = item;
                    break;
                }
                else if(item is JContainer)
                {
                    jModel = (item as JContainer).Get(id);
                }
            }
            
            if (jModel == null && this.Next != null)
            {
                jModel = this.Next.Get(id);
            }
            return jModel;
        }

        public List<JModel> ToList()
        {
            List<JModel> list = _collection.ToList();
            if (this.Next != null)
            {
                list.AddRange(this.Next.ToList());
            }
            return list;
        }

        public void Register(JContainerUpdate<JModel> update)
        {
            _update.Add(update);
        }

        public JCollection Link(JCollection nextContainer)
        {
            Next = nextContainer;
            return Next;
        }

        public List<T> GetChildren<T>() where T : JModel
        {
            List<T> list = new List<T>();
            foreach (var item in _collection)
            {
                if (item is T)
                {
                    list.Add((T)item);
                }
            }
            if (this.Next != null)
            {
                list.AddRange(this.Next.GetChildren<T>());
            }
            return list;
        }
    }
}
